<template>
  <div class="charge">
    <!-- Main Wrapper -->
    <div class="main-wrapper">
      <Header/>
      <SideBar/>

	<!-- Page Wrapper -->
	<div class="page-wrapper"><!-- :is="currentView" -->
		<div class="content container-fluid">
			<BreadCrumb/>
      <div class="yu-e"><span>我的余额：</span>{{surplus}}</div>
      <hr>
      <h2>帐户变更记录查询</h2>
      
      <el-main class="system">

        开始时间
        <el-date-picker
          v-model="startTime"
          type="datetime"
          placeholder="pls选择日期时间"
          value-format=" yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
          align="right"
          :picker-options="pickerOptions">
        </el-date-picker>

        结束时间
        <el-date-picker
          size="small"
          v-model="endTime"
          type="datetime"
          placeholder="pls选择日期时间"
          value-format=" yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
          align="right"
          :picker-options="pickerOptions">
        </el-date-picker>

        交易类型
        <el-select v-model="achoice" filterable placeholder="请选择">
          <el-option
            v-for="item in aoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>

        <el-button type="primary" @click="queryOprationLog">查询</el-button>
      </el-main>
		
		<el-main class="system">
		 
		  <div class="ends" >

        <el-button type="primary" class="sub" @click="chongzhi">充值</el-button>
        <el-button type="primary" class="tixian" @click="tixian">提现</el-button>
		    <el-button type="danger" class="">删除所选记录</el-button>

		  </div>
		
		  <div class="suoyou">
		    <el-table
		      border
		      style="width: 100%"
		      align="center"
		      @selection-change="handleSelectionChange"
		      :data="tableData"
		    >
		      <el-table-column type="selection" width="40" align="center"></el-table-column>
		              <el-table-column prop="accType" label="biz类型" :formatter="bizTypeFormatter"> </el-table-column>
                  <el-table-column prop="amountPaid" label="交易额" :formatter="bizAmountFormatter"> </el-table-column>
		              <el-table-column prop="afterSurplus" label="交易后余额"> </el-table-column>
		              <el-table-column prop="createTime" label="biz创建时间"> </el-table-column>
		   
		    </el-table>
		    <el-col :span="24" class="xtes">
		      <el-col :span="24" >
		        <div class="xtesbox">
		        <el-pagination
		                  @size-change="handleSizeChange"
		                  @current-change="handleCurrentChange"
		                  :current-page="currentPage"
		                  :page-sizes="[10, 20, 30, 40]"
		                  :page-size="pageSize"
						  class
		                  layout="total, sizes, prev, pager, next, jumper"
		                  :total="total"
		                >
		                </el-pagination></div>
		      </el-col>
		    </el-col>
		  </div>
		  
		</el-main>
      
		</div>
	</div>
	<!-- /Page Wrapper -->

    <el-dialog
	  title="提现"
	  :visible.sync="dialogVisible"
	  width="30%"
	  >
	   <span class="zhanghao">收款账号：</span><input class="account" type="text" id="account" name="account" placeholder="tel or email" v-model="account"><br>
	    <span class="zhanghao">真实姓名：</span><input class="account" type="text" id="realname" name="realname" placeholder="务必填写用于核验" v-model="realname"><br>
	    <span class="zhanghao">提现金额：</span><input class="account" type="text" id="money2" name="money2" placeholder="50.69(1RMB = 1Edu-Coin)"><br>
	    <span class="zhanghao">备注：</span><input class="account" type="text" id="remark" name="remark" placeholder="交易备注"><br>
      <el-button type="primary" @click="withdraw" >去提现</el-button>
      <!-- <input type="button" @click="withdraw" class="tiixan-btn" value="去提现"> -->
    <span slot="footer" class="dialog-footer">
	   <!-- <el-button @click="dialogVisible = false">取 消</el-button>
	    <el-button type="primary" @click="dialogVisible = false">确 定</el-button> -->
      
	  </span>
	</el-dialog>

<el-dialog
	  title="充值"
	  :visible.sync="dialogVisible2"
	  width="40%"
	  >
      <a href="https://sandbox.alipaydev.com/user/downloadApp.htm" target="_blank">点击去下载沙箱客户端</a>
      <span class="content-a">测试帐户gudrot4911@sandbox.com，登录密码同支付密码皆为111111</span>
      <br>
      <!-- <hr> -->
      <br>
      <form action="testpay" method="get">
          <span class="content-b">充值金额：</span><input type="text" class="money-input" id="money" name="money" placeholder="请输入充值金额"> (1RMB = 1Edu-Coin)<br>
          <el-button type="primary" @click="sub" >去支付</el-button>
          <!-- <input type="button" id="submit" @click="sub" value="去支付" class="submit"> -->
      </form>
</el-dialog>

    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import BreadCrumb from '@/components/Breadcrumb'
import Header from '@/components/Header'
import SideBar from '@/components/SideBar'
export default {
  created(){
    this.queryBalance();  // 首先进来初始化一次,然后每隔15s查一次余额
    this.timer = setInterval(this.queryBalance, 15000); // 左边的方法不需要加括号
	this.queryOprationLog();
  },
  beforeDestroy(){
    clearInterval(this.timer)
  },
  data(){
    return {
		currentPage: 1,
		pageSize: 10,
		total: 0,
    multipleSelection: [],
      // 不能带有空格缩进，会报错
      surplus: 'Balance',
      tableData:[],
      account: 'gudrot4911@sandbox.com',
      realname: '沙箱环境',
      // type下拉框
      aoptions: [{
          value: '1',
          label: '支出'
        }, {
          value: '2', 
          label: '收入'
        }, {
          value: '3',
          label: '充值'
        }, {
          value: '4',
          label: '提现'
        }
      ],
      achoice: '',
      // 时间选择器
      pickerOptions: {
        shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
        }]
      },
      startTime: '',
      endTime: '',
      dialogVisible: false,
      dialogVisible2: false
    }
  },
  mounted() {
  	// 全局挂载函数，单页面函数调用不推荐写到此处，也务必不能写到此处。这里只能写全局调用的组件的初始化等函数
  },
  methods: {
    // 判断金额是否正确，九位整数，三位小数
    sub(){
      // this.$domtool.pw($)
      // console.log(jQuery)
        var uid = localStorage.getItem('userId')
        var money = document.getElementById('money').value;
        // 金额必须符合  decimal(12,2)   //至多10位整数，至多2位小数
        var pattern = /^([1-9]\d{0,9}|0)([.]?|(\.\d{1,2})?)$/;
        if( ! pattern.test(money) ){
            alert( '请输入正确的金额' );
        }else if( pattern.test(money) ){
            let config = {
                method: 'get',
                url: 'edu/base/pay',
                params: {
                    amount: money,
                    stu_id: uid,
                    return_page: 'paySuccess'
                }
            };
            this.$http(config)
            .then((response)=>{
                /**
                 * 如果弹出：【沙箱支付】“支付存在钓鱼风险！防钓鱼网站的方法”
                 * 解决辦法：把浏览器上打开的所有沙箱支付、支付宝官方等的页面全部关闭，然后Crtl+Shift+delete,清空浏览器缓存。再试一下
                 */
                var myWindow=window.open(response.request.responseURL,'_blank');
                myWindow.document.write(response.data);
                myWindow.focus();
            
            }).catch(error => {
                this.$message.error("操作失败，请重试或者联系管理员");
                console.log(error)
            });
        }
    }, // sub() End
    tixian(){
      this.dialogVisible=true
    },
    chongzhi(){
      this.dialogVisible2=true
    },
    // 查询余额
    queryBalance(){
      let config = {
          method: 'post',
          url: 'edu/base/queryBalance',
          headers: {
            "Content-Type": "application/json;"
          },
          data: {
              u_id: localStorage.getItem('userId')
          }
      };
      this.$http(config)
      .then((response)=>{
        if (response.data.statusCode == 1){
          this.surplus = response.data.balance
        }else{
          throw new Error('错误');
        }
      }).catch(error => {
          this.$message.error("query failed, please try again later.");
          console.log(error)
      });
    }, //queryBalance()  End
    // 提现
    withdraw(){
      var money = document.getElementById('money2').value;
      // 金额必须符合  decimal(12,2)   //至多10位整数，至多2位小数
      var pattern = /^([1-9]\d{0,9}|0)([.]?|(\.\d{1,2})?)$/;
      if( ! pattern.test(money) ){
          alert( '请输入正确的金额' );
          return;
      }
      let config = {
          method: 'post',
          url: 'edu/base/accountWithdraw',
          headers: {
            "Content-Type": "application/json;"
          },
          data: {
              u_id: localStorage.getItem('userId'),
              eamil_tel: this.account,
              realname: this.realname,
              amount: money,
              remark: document.getElementById('remark').value===''?'无':document.getElementById('remark').value,
          }
      };
      this.$http(config)
      .then((response)=>{
        if(response.data.statusCode === 1){
          this.$message({
              message: response.data.msg,
              type: 'success',
              //type 取值 success(成功) /warning(警告)/info(消息)/error(错误)/;
          });
          this.dialogVisible = false
          this.queryBalance()
          this.queryOprationLog()
        }else{
          // 消息弹窗：方式一
          this.$message({
              message: response.data.msg,
              type: 'warning',
              //type 取值 success(成功) /warning(警告)/info(消息)/error(错误)/;
          });
        }
      }).catch(error => {
          this.$message.error("withdraw failed, please try again later.");
          console.log(error)
      });
    }, // withdraw  End()
    // 查询我的帐户变更记录
    queryOprationLog(){
      console.log(this.startTime)
      let config = {
          method: 'post',
          url: 'edu/base/queryAccountLog',
          headers: {
            "Content-Type": "application/json;"
          },
          data: {
              userId: localStorage.getItem('userId'),
              // 以下可改外动态参数
              pageNum: this.currentPage,
              pageSize: this.pageSize,
              startTime: this.startTime===null?'':this.startTime,
              endTime: this.endTime===null?'':this.endTime,
              bizType: this.achoice
          }
      };
      this.$http(config)
      .then((response)=>{
        // 待实现数据分页
        if ( response.data.statusCode === 1 ){
          this.$message.success("查询成功");
          this.tableData=response.data.page.list
          this.total=response.data.page.totalCount
        }else{
          this.$message.warning(response.data.msg);
        }
      }).catch(error => {
          this.$message.error("query failed, please try again later.");
          console.log(error)
      });
    }, // queryOprationLog() End
	handleSizeChange(val) {
	  this.pageSize = val;
	  this.queryOprationLog();
	  // console.log(`每页 ${val} 条`);
	},
	handleCurrentChange(val) {
	  this.currentPage = val;
	  this.queryOprationLog();
	  // console.log(`当前页: ${val}`);
	},
  handleSelectionChange(data) {
    // console.log('获取row', data)
    // 当前多选的数据
    this.multipleSelection = data;
  },
    bizTypeFormatter(data){
      if(data.accType == 1){
          return '支出'
      }
      if(data.accType == 2){
          return '收入'
      }
      if(data.accType == 3){
          return '充值'
      }
      if(data.accType == 4){
          return '提现'
      }
    },
    bizAmountFormatter(data){
      if(data.accType == 1 || data.accType == 4){
          return '-' + data.amountPaid
      }
      if(data.accType == 2 || data.accType == 3){
          return '+' + data.amountPaid
      }
    }
  },
  components: {
    Header,
    BreadCrumb,
    SideBar
  }
}
</script>
<style >
	.yu-e{
		/* color: #009CE7; */
		font-size: 25px;
		/* margin-top: 20px; */
		margin-bottom: 20px;
	}
	.content-a{
		margin-left: 60px;
	}
	.content-b{
		font-size: 18px;
	}
	.money-input{
		width: 300px;
		height: 35px;
		padding-left: 10px;
		
	}
	.submit{
		width: 100px;
		height: 35px;
		background-color: #6ec1fd;
		border-radius: 5px;
		margin-top: 30px;
		margin-left: 350px;
		/* margin-bottom: -20px; */
		border: none;
		color: #fff;
	}
	.tixian{
		/* font-size: 25px; */
		margin-bottom: 15px;
	}
	.zhanghao{
		font-size: 18px;
		width: 100px;
		height: 50px;
	}
	.account{
		width: 200px;
		height: 35px;
		margin-bottom: 20px;
		padding-left: 10px;
	}
	.tiixan-btn{
		width: 100px;
		height: 35px;
		background-color: #6ec1fd;
		border-radius: 5px;
		margin-top: 30px;
		margin-left: 350px;
		/* margin-bottom: -20px; */
		border: none;
		color: #fff;
	}
	.system {
	  background-color: #fff;
	  border-radius: 0 0 15px 15px;
	  font-size: 18px;
	  /* .zlsou {
	    float: left;
     
	  }
	  .zltext {
	    line-height: 40px;

	  }
	  .zlxila {
	    margin-right: 20px;
		width: 100px;
	  } */
	}
	.sub{
		margin-left: 30px;
	}
	.ends {
	  margin-bottom: 20px;
	  
	}
	.xtes {
	  margin-top: 20px;
	  margin-bottom: 20px;
	}
	.xtesbox{
	  float: right;
	  padding-right: 150px;
	}
</style>
